# 窗口的感知和刷新设置
"""
1、pygame.display.get_active()
作用：用于感知窗口是否被最小化
参数：无
返回值：
    True 表示没有被最小化
    False表示被最小化了

2、pygame.display.flip()
作用：重新绘制全部窗口图像
参数：无
返回值：无

3、pygame.display.update()
作用：仅仅重新绘制改变部分的图像，这样在场景变化频繁的情况下很实用
参数：无
返回值：无
"""
import os
import sys
import pygame

pygame.init()

# vInfo = pygame.display.Info()
# size = width, height = vInfo.current_w, vInfo.current_h
size = width, height = 1000, 600
screen = pygame.display.set_mode(size, flags=pygame.RESIZABLE)
pygame.display.set_caption('小仓鼠')

WHITE = (255, 255, 255)
speed = [1, 1]
fps = 100

BASE_DIR = os.path.realpath(os.path.dirname(sys.argv[0]))
BALL_DIR = os.path.join(BASE_DIR, 'ball.gif')
MUSIC_DIR = os.path.join(BASE_DIR, 'music.mp3')
SOUND_DIR = os.path.join(BASE_DIR, 'en.mp3')
ICON_DIR = os.path.join(BASE_DIR, 'rat.png')

icon = pygame.image.load(ICON_DIR)
pygame.display.set_icon(icon)


ball = pygame.image.load(BALL_DIR)
ball_rect = ball.get_rect()

pygame.mixer.music.load(MUSIC_DIR)
pygame.mixer.music.play()
sound = pygame.mixer.Sound(SOUND_DIR)

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.VIDEORESIZE:  # 是VIDEORESIZE不是RESIZABLE
            print('调整了窗口')
            size = width, height = event.size[0], event.size[1]
            screen = pygame.display.set_mode(size, flags=pygame.RESIZABLE)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                speed[1] += 3
            elif event.key == pygame.K_UP:
                speed[1] -= 3
            elif event.key == pygame.K_LEFT:
                speed[0] -= 3
            elif event.key == pygame.K_RIGHT:
                speed[0] += 3
            if event.key == pygame.K_SPACE:
                speed[0] = 0
                speed[1] = 0
            if event.key == pygame.K_ESCAPE:
                sys.exit()
    if abs(speed[0]) > 5:
        speed[0] = 5 * int(speed[0] / abs(speed[0]))
    if abs(speed[1]) > 5:
        speed[1] = 5 * int(speed[1] / abs(speed[1]))

    if pygame.display.get_active():
        ball_rect = ball_rect.move(speed[0], speed[1])

    if ball_rect.left < 0 or ball_rect.right > width:
        speed[0] = -speed[0]
        pygame.mixer.Sound.play(sound)
    if ball_rect.top < 0 or ball_rect.bottom > height:
        speed[1] = -speed[1]
        pygame.mixer.Sound.play(sound)

    screen.fill(WHITE)
    screen.blit(ball, ball_rect)
    clock.tick(fps)
    pygame.display.update()

